<?php
class Admin_PageController extends Zend_Controller_Action
{
	private $t;
	private $hash;

	public function preDispatch()
	{
		$this->t = Zend_Registry::get('Zend_Translate');
		$this->view->t = $this->t;
	}

	public function listAction()
	{
		$this->view->title = $this->t->_('all pages');

		$pages = new Pages();
		$this->view->pages = $pages->generateTree();

		/* test */
		$this->view->english = $pages->generateTree(1);
		$this->view->dutch = $pages->generateTree(2);
		$this->view->chinese = $pages->generateTree(4);
	}

	public function saveAction()
	{
		$form = new PageForm();

		$this->view->title = $this->t->_('save page');
		$this->view->form = $form;

		$id = (int) $this->_request->getParam('id');

		$pages = new Pages();

		$form->parentId->setMultiOptions( $this->_helper->parsePageTree($pages->generateTree()) );

		$page = $pages->fetchRow("`id` = '{$id}'");

		if($page == NULL) {
			$page = $pages->createRow();
		}

		$languages = new Languages();
		$allLanguages = $languages->fetchAll();
		$pagesL10NArray = array();
		$pagesL10N = new PagesL10N();

		foreach($allLanguages as $language) {
			$subform = new PageL10NForm();
			$subform->setLegend($language->name);
			$form->addSubForm($subform, 'language' . $language->id, $language->id);

			$pagesL10NArray[$language->id] = $pagesL10N->fetchRow(array("`pageId` = '{$id}'", "`languageId` = '{$language->id}'"));

			if($pagesL10NArray[$language->id] == NULL) {
				$pagesL10NArray[$language->id] = $pagesL10N->createRow();
				$pagesL10NArray[$language->id]->languageId = $language->id;
			}
		}

		if($this->_request->isPost()) {
			$formData = $this->_request->getPost();
			if($form->isValid($formData)) {

				$page->parentId = $form->getValue('parentId');
				if($page->parentId == NULL) {
					$page->parentId = 0;
				}
				$pageId = $page->save();

				$subforms = $form->getSubForms();
				$pagesL10N->delete(array("`pageId` = '{$id}'", "`name` = ''"));

				foreach($subforms as $subform) {
					$languageId = $subform->getValue('languageId');

					if($subform->getValue('name') != '') {
						$pagesL10NArray[$languageId]->name = $subform->getValue('name');
						$pagesL10NArray[$languageId]->pageId = $pageId;
						$pagesL10NArray[$languageId]->languageId = $languageId;
						$pagesL10NArray[$languageId]->save();
					} elseif(is_numeric($languageId) && is_numeric($pageId)) {
						$pagesL10N->delete(array("`pageId` = '{$pageId}'", "`languageId` = '{$languageId}'"));
					}
				}
			}
		} else {
			$form->populate($page->toArray());

			foreach($allLanguages as $language) {
				$form->getSubForm('language' . $language->id)->populate($pagesL10NArray[$language->id]->toArray());
			}
		}
	}

	public function deleteAction()
	{

	}
}